/**/
package org.gd.spring.mongodb;

import com.mongodb.DBCollection;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

public class UpdateDocumentsExample {

    public static void main(String[] args) {

        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
        MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");

        mongoOperation.remove(new Query(), "yourCollection");
        mongoOperation.remove(new Query(), "user");
        //mongoOperation.remove(new Query(), "users");

        String collectionName = "users";
        DBCollection dbCollection = mongoOperation.getCollection(collectionName);
        String idInMongoDB = "id";
        Long id = System.currentTimeMillis();

        User1 user = new User1(id, "user-first", "user-last", 17);
        // Case 1 ... update object
        System.out.println("Case 1...by save()");
        // Save user object
        mongoOperation.save(user, collectionName);

        System.out.println(" --- ONE: \n" + mongoOperation.findOne(new Query(Criteria.where(idInMongoDB).is(id)), User1.class, collectionName));

        // Update user object, lastname
        mongoOperation.save(user.setLastname("new last name"), collectionName);
        System.out.println(" --- ONE: \n" + mongoOperation.findOne(new Query(Criteria.where(idInMongoDB).is(id)), User1.class, collectionName));

        // Case 2 ... update firstname field, $set
        System.out.println("Case 2...by updateFirst() - $set");
        mongoOperation.updateFirst( new Query(Criteria.where(idInMongoDB).is(id)), Update.update("firstname", "new first name"), collectionName);
        System.out.println(" --- ONE: \n" + mongoOperation.findOne(new Query(Criteria.where("id").is(id)), User1.class, collectionName));

        // Case 3 ... update age field, $inc
        System.out.println("Case 3...by updateFirst() - $inc");


        System.out.println("\n --- ONE: \n" + mongoOperation.findAndModify(
                new Query(Criteria.where(idInMongoDB).is(id)),
                new Update().inc("age", 10),
                new FindAndModifyOptions().returnNew(true),
                User1.class,
                collectionName));

        System.out.println("\n --- ALL: \n" + mongoOperation.findAll(User1.class, collectionName).toString().replace(", User1", ",\n User1"));



    }

}

